//本文件处理充电状态&&扫码逻辑
const app = getApp();
//#ifdef H5
import { isWeiXin, initH5Config } from './h5.js';
//#endif
import { isChangzhi, isZshAppInH5 } from './util.js';

import {
    querMemberStatus,
    parseCode,
    queryQrcodeData,
    getGunDTOByConnectorId
} from './../api/https.js'; // 解析扫码字符串

// 解析url参数 *?{key}={val}通配
function extractUrlParams(url) {
    // const obj ={}
    // const url = new URL(urlStr);
    // const urlParams = new URLSearchParams(url.search);
    // urlParams.forEach((value, key) => {
    //     obj[key] = value
    //     // console.log(`${key}: ${value}`);
    // });
    // return obj
    url = url.substring(url.indexOf('?') + 1)
    const str = url.split('&')
    const url_arr = {}
    for (let i = 0; i < str.length; i++) {
        const sttr = str[i].split('=') // sttr = [aaa,123]
        url_arr[sttr[0]] = sttr[1] // [aaa:"123"]
    }
    return url_arr
}


const regJw = /[0-9A-Za-z]/  
var jw;    
var  sellerNoGy = ''      
// 椰速充规则
function getYscCode(code) {
    let url = code
    url = url.substring(url.indexOf('?') + 1)
    const str = url.split('&')
    const url_arr = {}
    for (let i = 0; i < str.length; i++) {
        const sttr = str[i].split('=') // sttr = [aaa,123]
        url_arr[sttr[0]] = sttr[1] // [aaa:"123"]
    }
    return url_arr
}
 
function analysis(code) {
	console.log(code,'啦啦啦啦二维码')
	
	code = code.trim()

    // 小蓝规则-二轮充电
    const landCodeRule = /^http.*chargeland.cn.*code=.*/
    // https://wx.chargeland.cn/qcode?code=01012000267_10
	
	// 巨湾规则-润云
	const jwCodeRule1 = /^http.*newtest.sz-rcdxny1.com.*organizationCode=.*/
	// 参考示例:https://newtest.sz-rcdxny1.com/wechat?organizationCode=555555,5245416512111
	
	// 巨湾规则
	const jwCodeRule = /^http.*app-api.zyun.link.*pileSn=.*/
	// 参考示例:https://app-api.zyun.link/?gunSn=01&pileSn=04401000000003
	
	// 巨湾CAMS
	const RexCAMSCode =  /^http.*qrcode.camsnetec.com.*(\d{8})$/
	// 参考示例:https://qrcode.camsnetec.com/#/10073094
	
    // 巨湾速电通
    const RexGetSdtCode =  /^http.*gateway.chargetong.cn.*gunCode=.*$/  
    // https://gateway.chargetong.cn/storage/gun/scan-to-charge?gunCode=003552000001000101
   
    // 巨湾椰速充
    const RexGetYscCode = /^http.*scanCode=.*/
    const RexYsc2Code =   /^hlht.*\.MA59G0765\/.*?orgNo=MA5TEL7Y9/   // hlht://枪号.MA59G0765/桩编号?orgNo=桩运营商ID  
    
     // 顺丰云快充
    const RexYkccnCode =  /^http.*pNum=.*$/ //http://www.ykccn.com/MPAGE/index.html?pNum=3201060000071002
    const RexNum = /^[0-9]+$/; // 纯数字  000000000001212121
 
    const RexNum1 = /^[0-9]+-[0-9]+$/; //  11111111-1
 
    const RexNum2 = /^[0-9]+_[0-9]+$/ // 0000000086800012_2  康亿创-光烨解析

    const RexNum3 = /^\d{10}@2$/ // 10位纯数字@2  二轮充电
    const httpsRexNum3 = /^http.*?pileNo=*\d{10}@2.*$/ // 二轮充电-带域名
    
    const RexHttpGY = /^http.*pileNo=.*gunNo=.*sellerNo=.*$/ // http://mp.gy-ev.com/weixin/gunnoList?pileNo=11270010&gunNo=0&connectorid=4152&sellerNo=yckc
    const RexHttp =  
    /^http.*pileNo=.*gunNo=.*$/; // http格式  http://gjxny.gzeryun.com/weixin/gunnoList?pileNo=1527017&gunNo=0
           
    const RexDevice = /^http.*device=.*$/; // 捷电通  http://jdt.wx.gzjiediantong.com/app/download?device=11112222333344445
 
    const Rex66 = /^http.*data=.*$/;
    /** 66二维码      
      1 http://www.66ifuel.com/scans/result.html?data=6700010
      2 http://www.66ifuel.com/scans/result.html?data=31100057002000201
      3 http://www.66ifuel.com/scans/result.html?data=AC6600007
      4 http://www.66ifuel.com/scans/result.html?data=2067-00010
      5 http://www.66ifuel.com/scans/result.html?data=AC66-00008
      */
 
    const RexGyDg =
    /^http.*wx.zb-ev.com.*$/; // http://wx.zb-ev.com/SN/start/SN10K051940400011 光烨-与东莞众邦互联互通二维码适配//http格式
 
    const RexWM = /^type=cdz.*\d$/; // type=cdz&code=3301061019321443&q=1 万马二维码 桩：code=3301061019321443 枪：q=1
 
    const RexZL =
    /^http.*zl-c.cn.*\d$/; // 致联 //code = https://zl-c.cn/1998010203/01 ||  https://zl-c.cn/terminal_number=1998010203&gun_number=01
    
    const RexHLHTLX = /^hlht:\/\/.*\/.*\..*\//; // 理想规则：如：hlht://MA7EBGWBX/81022231.MA6ARPET9/
    const RexHLHT = /^hlht:\/\/.*\/.*/;
    /**  车电网二维码符合互联互通规范，生成规则为： hlht://充电设备接口ID.运营商ID/[自定义]
   特来电二维码符合互联互通规范，生成规则为：hlht://充电设备接口ID.运营商ID/
   劲桩二维码符合互联互通规范,生成规则为： hlht://充电设备接口ID.运营商ID/
  */
 
    const RexSJ =  /^hlht:\/\/.*\..*\/.*/  // 省交 hlht://connector_id.EquipmentOwnerID/gunid
 
    const RexWCWC = /^http.*qrcode=.*$/; // 万城万充二维码格式 示例:http://www.gdmcmc.cn/qrcode.html?qrcode=881011000032
 
    const RexXXCD = /^http.*\/#\/\d*$/; // 星星充电
 
    const RexQMX = /^AOSTAR_CODE:H\d+$/; // 启明星二维码 'AOSTAR_CODE:H1210000000010039'
 
    const RexTWT = /^http.*help.html?.*$/; // 特瓦特二维码规则为： http://h5.towatt.com/weixin/pro/pay/help.html?充电设备接口ID
 
    const RexNw =
    /^http.*grcode?.*grcode.*$/; // 南网二维码规则为： https://www.wodeev.com/ast/api/v0.1/guns/grcode?pileNo=0900271812070002&gunNo=0&grcode=090027181207000201
 
    const RexJw1 = /^http.*code=.*$/; // 泰明-适配蔚景云二维码 格式1
 
    const RexJw2 = /^hlht.*orgNo=.*$/; // 泰明-适配蔚景云二维码 格式2 互联互通
 
    const RexJuW = /^http.*\/base\/ast\/scan\/.*$/; // 巨湾  https://www.ts-evic.com/base/ast/scan/S0119070801/5805005_1
 
    const RexZH =
    /^http.*pileNo=[0-9]{9}.*gunNo=.*$/; // http格式  http://gjxny.gzeryun.com/weixin/gunnoList?pileNo=1527017&gunNo=0
 
    const RexZhoH =
        /^http.*\/epower\/static\/resources\/xcxconf\/.*$/ // 小桔1  https://epower.xiaojukeji.com/epower/static/resources/xcxconf/XIAOJU.101437000.04221909157601
 
 
    //test2day.ecnne.com/weixin/#/gunList?pileNo=07550010111&gunNo=01
    // const RexSh = /^http.*\/#\/[0-9]*$/           // 盛宏 https://qrcode.starcharge.com/#/202112160101
    const RexHLHT2 = /^hlht:\/\/.*MA5DA0053\/.*/ // hlht://充电设备接口ID.运营商ID/[自定义]-车电网
    const RexANLJ = /^http.*xiaojukeji.com.*xcxconf\/.*$/
    /** 安能绿捷
                                                                1、https://epower.xiaojukeji.com/epower/static/resources/xcxconf/XIAOJU.小桔运营商.枪号
                                                                   https://epower.xiaojukeji.com/epower/static/resources/xcxconf/XIAOJU.101437000.04221909157601
                                                                2、https://epower.xiaojukeji.com/epower/static/resources/xcxconf/枪号
                                                                   https://epower.xiaojukeji.com/epower/static/resources/xcxconf/04221909157601
                                                                */
    const RexGw1 = /^hlht:\/\/.*MA002TMQX\/.*/ // 国网
    const RexGw2 = /^http.*\echargenet.com.*$/ // 国网
    const WanMa = /^http.*\eichong.com.*$/ // 万马
    const RexNr = /^http.*nrcdcmp.*$/ // 能瑞
    const RexHK =
        /^https.*test04-manage.iot.renwochong.com.*$/ // http格式  http://wechat.iot.renwochong.com/pl/0101810067000001
    const RexBZ = /^http.*powerbanc.cn.*$/ // http格式  https://www.powerbanc.cn/qr?inst=8900&sn=${gunCode}
    const RexLs = /^https.*www.charge-i.com\/cd.html.*$/      // 海口量势二维码二维码规则 https://www.charge-i.com/cd.html?c=XXXXXXXX-Y
 
    const RexJw3 = /^http.*wx.evking.cn.*code=.*$/ // http://wx.evking.cn/app/download?code={枪号} http://wx.evking.cn/app/download?orgNo={运营商编号}&code={枪号}
 
    const RexJw4 =   /^hlht.*\..*\/.*?orgNo=.*/  // hlht://枪号.MA59G0765/桩编号?orgNo=桩运营商ID  
    const RexJw5 =   /^http.*wx.yescharge.cn.*orgNo=.*code=.*$/  // hlht://枪号.MA59G0765/桩编号?orgNo=桩运营商ID(已加未测)
   
    // 小程序 & 支付宝小程序跳转逻辑 - codeFusion
    // 如：https://hccn.info/codeFusion/#/gunnoList?connectorID=81002837&sellerNo=tjhz
    const RexCodeFusion = /^http.*codeFusion.*connectorID=.*sellerNo=.*$/;
    
    console.log(code,'code')  
    /**星星充电二维码格式格式
  1.单枪二维码
    终端编号：10050638
    二维码格式1：10050638
    二维码格式2：https://qrcode.starcharge.com/#/10050638
    互联互通编号（ConnectorID）：11000000000000010050638000
     2.双枪二维码
    终端编号：1012081501
    二维码格式1：1012081501
    二维码格式2：https://qrcode.starcharge.com/#/1012081501
    互联互通编号（ConnectorID）：12000000000000010120815001
  */
	// if (app.globalData.switchLog) {
        console.log('httpsRexNum3:>> ', httpsRexNum3.test(code))
        console.log('RexNum3:>> ', RexNum3.test(code))
        console.log('landCodeRule:>> ', landCodeRule.test(code))
		console.log('jwCodeRule1:>> ', jwCodeRule1.test(code))
		console.log('jwCodeRule:>> ', jwCodeRule.test(code))
		console.log('RexGetSdtCode.test(code) :>> ', RexGetSdtCode.test(code))
		console.log('RexNum.test(code) :>> ', RexNum.test(code));
		console.log('RexNum1.test(code) :>> ', RexNum1.test(code));
		console.log('RexNum2.test(code) :>> ', RexNum2.test(code))
		console.log('RexHttp.test(code) :>> ', RexHttp.test(code));
		console.log('RexHttpGY.test(code) :>> ', RexHttpGY.test(code));
		console.log('RexDevice.test(code) :>> ', RexDevice.test(code));
		console.log('RexGyDg.test(code) :>> ', RexGyDg.test(code));
		console.log('RexWM.test(code) :>> ', RexWM.test(code));
		console.log('RexZL.test(code) :>> ', RexZL.test(code));
        console.log('RexHLHTLX.test(code) :>> ', RexHLHTLX.test(code));
		console.log('RexHLHT.test(code) :>> ', RexHLHT.test(code));
		console.log('RexSJ.test(code) :>> ', RexSJ.test(code))
		console.log('RexWCWC.test(code) :>> ', RexWCWC.test(code));
		console.log('RexXXCD.test(code) :>> ', RexXXCD.test(code));
		console.log('RexQMX.test(code) :>> ', RexQMX.test(code));
		console.log('Rex66.test(code) :>> ', Rex66.test(code));
		console.log('RexTWT.test(code) :>> ', RexTWT.test(code));
		console.log('RexNw.test(code) :>> ', RexNw.test(code));
		console.log('RexZH.test(code)：>>', RexZH.test(code));
		console.log('RexHLHT2.test(code) :>> ', RexHLHT2.test(code))
		console.log('RexANLJ.test(code) :>> ', RexANLJ.test(code))
		console.log('RexGw1.test(code) :>> ', RexGw1.test(code))
		console.log('RexGw2.test(code) :>> ', RexGw2.test(code))
		console.log('WanMa.test(code) :>> ', WanMa.test(code))
		console.log('RexNr.test(code) :>> ', RexNr.test(code))
		console.log('RexBZ.test(code) :>> ', RexBZ.test(code))
		console.log("RexZhoH.test(code)：>>", RexZhoH.test(code))
		console.log('RexLs.test(code) :>> ', RexLs.test(code))
		console.log("RexJw3.test(code)：>>",RexJw3.test(code)) 
		console.log("RexJw4.test(code)：>>",RexJw4.test(code))
		console.log("RexJw5.test(code)：>>",RexJw5.test(code))
        console.log("RexCodeFusion.test(code)：>>",RexCodeFusion.test(code))
	// }

	let pileNo = '';
	let gunNo = ''; // 纯数字
	 let codeSellerType = ''; //速电通
	let kycText = ''; //康亿创取值
	let runYunConnectorId = ''; //是否润云扫码规则ID,用于接口解析桩枪号
    let terminalType = 1;  // 1-是四轮充电、2-二轮充电
    let platformNo = '' // 域名
    let connectorID = '' // 完整枪号

	try {
		// debugger
		if (RexNum.test(code)) {
            const { sellerNo } = getApp().globalData
            // 给中燃做了处理，纯数字2021开头不走星星充电的8位
            // let reg = RegExp(/2021/);
            // let tg = code.match(reg)
            // 给华澈新能源纯10位数字做的处理，纯数字1911、、1181开头不走星星充电的10位
            // 3938是8位
            // let reg2 = RegExp(/1911/);
            // let reg3 = RegExp(/3938/);
            // let reg4 = RegExp(/1181/);
            // let tg2 = code.match(reg2)
            // let tg3 = code.match(reg3)
            // let tg4 = code.match(reg4)

			if (code.length === 21) {
				pileNo = code.substring(0, code.length - 1); // 00000000002019072901

				gunNo = code[code.length - 1] * 1 - 1; // 1
			}
			//夏门星星充电 互联互通补充纯数字根据位数
			else if (sellerNo == 'xmgj' && code.length === 8) {
				// 单枪
				pileNo = '110000000000000'+code+'000'; // 10050638
				gunNo = -1
			}else if (sellerNo == 'xmgj' && code.length === 10) {
				// 双枪
				let codeStr = code.substr(0, 8);
				pileNo = '120000000000000'+ codeStr; // 8272360501
				gunNo = -1
			} else {
				pileNo = code; // 100006

				gunNo = -1; // 只有桩号显示全部枪
			}
		} else if (RexCAMSCode.test(code)) {
			//巨湾CAMS
			let num = code.split('#/')[1]
			
			if(num.length == 8){
				pileNo = '210000000000000'+num+'000';
			}
			
			if(num.length == 10){
                pileNo = '220000000000000'+num.substring(0,8)
				// pileNo = '220000000000000'+num.substring(0,8)+ '0'+ num.substring(8,10);
			}
			gunNo = -1
			console.log(`巨湾CAMS,${num.length}位桩号${pileNo},桩号位数${pileNo.length}`)
		} else if (jwCodeRule.test(code)) {
			let data = getYscCode(code)
			pileNo = data.pileSn
			gunNo = parseInt(data.gunSn)
			console.log(`巨湾规则jwCodeRule:桩号${pileNo},枪号${gunNo}`)
		} else if (jwCodeRule1.test(code)) {
			let organizationCode = getYscCode(code).organizationCode.split(',')
			console.log(organizationCode,'这个啦啦')
			runYunConnectorId = organizationCode[1]
			console.log(`巨湾润云规则jwCodeRule1: 解析号${organizationCode[1]},用于接口解析`)
		} else if(landCodeRule.test(code)) { 
            const response = extractUrlParams(code)
            console.log('二轮',response)
            pileNo =  response.code.split('_')[0]
            gunNo = response.code.split('_')[1]
            // 小蓝01-09开头的桩号为二轮充电桩
            if(pileNo.substring(0,2) < 10) {
                terminalType = 2
            }

        } else if(RexNum3.test(code)) {
            terminalType = 2
            pileNo = code.split('@')[0]
            gunNo = -1
        }else if(httpsRexNum3.test(code)) {
            terminalType = 2
            let arrData = getYscCode(code).pileNo
            pileNo = arrData.split('@')[0]
            gunNo = getYscCode(code).gunNo
        }
		 else if (RexNum1.test(code)) {
			// 11111111-1
			pileNo = parseInt(code); // 100043

			gunNo = code[code.length - 1]; // '1'
			// http格式
		} else if (RexNum2.test(code)) { // 0000000086800012_2
			console.log(code,'康亿创........')
            kycText = code
 
            let codeJoin = code.split('_')
            console.log(codeJoin)
            pileNo = codeJoin[0]
            gunNo = Number(codeJoin[1]) - 1
            console.log(pileNo, gunNo)
        } else if (RexWM.test(code)) {
            // 万马 没有乱码情况
            const wMStrs = code.split('&');
            pileNo = wMStrs[1].split('=')[1]; // 100006
 
            gunNo = wMStrs[2].split('=')[1] - 1; // 只有桩号显示全部枪
            // gunNo = '' // 万马枪号传空
        } else if (RexHK.test(code)) {
            let codestr = code.split('https://test04-manage.iot.renwochong.com/pl/')[1]
            pileNo = codestr.slice(0, 14)
            gunNo = codestr.slice(14)
        }else if(RexLs.test(code)){
            let codestr = code.split('=')   
            pileNo = ''
            gunNo = codestr[1]        
        }else if (RexHttpGY.test(code)) {
			// 网址带桩号 枪号 二维码
			// http格式
			let url = code;
			url = url.substring(url.indexOf('?') + 1);
			const str = url.split('&');
			const url_arr = [];
			 
			for (let i = 0; i < str.length; i++) {
				const sttr = str[i].split('='); // sttr = [aaa,123]
			 
				url_arr[sttr[0]] = sttr[1]; // [aaa:"123"]
			}
			pileNo = url_arr.pileNo;
			gunNo = url_arr.gunNo;
			pileNo = parseInt(pileNo);  
			sellerNoGy = url_arr.sellerNo 
        }else if (RexZH.test(code)) {
            let url = code;
            url = url.substring(url.indexOf('?') + 1);
            const str = url.split('&');
            const url_arr = [];
 
            for (let i = 0; i < str.length; i++) {
                const sttr = str[i].split('='); // sttr = [aaa,123]
 
                url_arr[sttr[0]] = sttr[1]; // [aaa:"123"]
            }
 
            pileNo = url_arr.pileNo;
            gunNo = url_arr.gunNo;
        } else if (/^http/.test(code)) {
            let url = code;
            url = url.substring(url.indexOf('?') + 1);
            const str = url.split('&');
            const url_arr = [];
 
            for (let i = 0; i < str.length; i++) {
                const sttr = str[i].split('='); // sttr = [aaa,123]
 
                url_arr[sttr[0]] = sttr[1]; // [aaa:"123"]
            }
            if (RexGw2.test(code) || RexNr.test(code)) { // 国网 || 能瑞
                decode2(code);   
                return;
            }else if (RexGetSdtCode.test(code)) { // 速电通
                 console.log('=====RexGetSdtCode',code)
                let qrcode = getYscCode(code).gunCode
                console.log(qrcode)
                pileNo = qrcode
                gunNo = -1
                codeSellerType = 'sudiantong'
            }else if (RexHttp.test(code)) {
                // 网址带桩号 枪号 二维码
                // http格式
                pileNo = url_arr.pileNo;
                gunNo = url_arr.gunNo;
                const regex = /[a-zA-Z]/
                if(!regex.test(pileNo)) {
                    pileNo = parseInt(pileNo);
                }
                
            } else if (RexGetYscCode.test(code)) { // 椰速充
                console.log('=====RexGetYscCode')
                let qrcode = getYscCode(code).scanCode
                console.log(qrcode)
                pileNo = qrcode
                gunNo = -1
            }  else if(RexYkccnCode.test(code)){ //云快充
                console.log('云快充',url_arr.pNum)
                const pNum = url_arr.pNum
                   pileNo = -1
                   gunNo = pNum
                
            } else if (RexZhoH.test(code)) { //小桔
                 console.log(code,'code11')
                const codeArr = code.split('.')
                pileNo = ''
                if (codeArr.length >= 5) {
                    gunNo = codeArr[4]
                } else {
                    const urlArr = code.split('/')
                    const urlStr = urlArr[urlArr.length - 1]
                    gunNo = urlStr
                }
                
                console.log(gunNo,'gunNo')
            } else if (RexDevice.test(code)) {
                // 捷电通分16位与17，18位
                const device = url_arr.device;
 
                if (device.length === 16) {
                    // 16数
                    pileNo = device;
                    gunNo = -1;
                } else {
                    pileNo = '';
                    gunNo = device;
                }
            } else if (RexGyDg.test(code)) {
                // 光烨东莞互联互通
                const urlArr = code.split('/');
                const urlStr = urlArr[urlArr.length - 1];
                pileNo = urlStr.slice(0, urlStr.length - 1);
                gunNo = urlStr.slice(-1) * 1 - 1;
            } else if (RexZL.test(code)) {
                // 致联 https://zl-c.cn/1998010203/01
                const num = code.match(/\d+/g);
 
                if (num.length === 1) {
                    // code = https://zl-c.cn/1998010203/01
                    const codeStr = num[0];
                    pileNo = codeStr.substring(0, codeStr.length - 2);
                    gunNo = codeStr.substring(codeStr.length - 2) - 1;
                } else if (num.length === 2) {
                    // https://zl-c.cn/terminal_number=1998010203&gun_number=01
                    pileNo = num[0];
                    gunNo = num[1] - 1;
                } else {
                    // ('未能识别二维码1')
                    return {
                        err: true
                    };
                }
            } else if (RexWCWC.test(code)) {
                // 万城万充二维码格式 示例:http://www.gdmcmc.cn/qrcode.html?qrcode=881011000032
                pileNo = '';
                gunNo = url_arr['qrcode'];
            } else if (RexXXCD.test(code)) {
                // 星星充电网址二维码
                const rexArr = code.match(/\/#\/(.*)/);
                const str = rexArr[1]; // 转化成互联互通编号
 
                if (str.length == 8) {
                    pileNo = '';
                    gunNo = `110000000000000${str}000`;
                } else if (str.length == 10) {
                    // 1005063801
                    const pileN = str.slice(0, 8);
                    const gunN = str.slice(8);
                    pileNo = '';
                    gunNo = `120000000000000${pileN}0${gunN}`;
                } else if (str.length == 12) {
                    // 202112160101    暂时用于盛宏
                    const pileN = str.slice(0, 10);
                    const gunN = str.slice(10);
                    pileNo = pileN;
                    gunNo = Number(gunN) - 1;
                }
            } else if (Rex66.test(code)) {
                // 66二维码
                let data = url_arr.data;
 
                if (data.indexOf('-') != -1) {
                    // 不含 -
                    data = data.replace('-', '');
 
                    if (data.indexOf('AC') == -1) {
                        //data不含AC
                        //4 http://www.66ifuel.com/scans/result.html?data=2067-00010
                        if (data.length == 9) {
                            data = data.slice(2); // 去除前两位
                        }
                    }
                }
 
                pileNo = '';
                gunNo = data;
            } else if (RexNw.test(code)) {
                // 南网二维码规则为
                const grcode = url_arr.grcode;
                pileNo = '';
                gunNo = grcode;
            } else if (RexTWT.test(code)) {
                // 特瓦特
                let codeArr = code.match(/\?(.*)/);
                pileNo = '';
                gunNo = codeArr[1];
            }else if(RexJw5.test(code)){
                let codeArr = code.split('code=')            
                pileNo = ''
                gunNo=codeArr[1]     
            }else if(RexJw3.test(code)){      
                let codeArr = code.split('code=')            
                pileNo = ''
                gunNo=codeArr[1]
                jw = regJw.test(gunNo)
            }else if (RexJw1.test(code)) {
                // // 泰明-适配蔚景云二维码 格式1
                pileNo = -1;
                gunNo = url_arr.code;
            } else if (RexJuW.test(code)) {
                // https://www.ts-evic.com/base/ast/scan/S0119070801/5805005_1
                const codeArr = code.split('/');
                const pileArr = codeArr[codeArr.length - 1].split('_');
                pileNo = pileArr[0];
                gunNo = pileArr[1];
            } else if (RexANLJ.test(code)) { //安能绿捷-小桔
                const codeArr = code.split('/')
                const pileArr = codeArr[codeArr.length - 1].split('.')
                pileNo = ''
                gunNo = pileArr[pileArr.length - 1]
            } else if (WanMa.test(code)) { //万马
                pileNo = code.substring(code.indexOf("epCode=") + 7, code.indexOf("&epHead="));
                gunNo = code.substring(code.indexOf("&epHead=") + 8, code.indexOf("|")) - 1;
                console.log(gunNo, 'gunNogunNogunNogunNo')
 
            } else if (RexBZ.test(code)) { // 保泽
                decode3(code);
                return;
            } else if (RexCodeFusion.test(code)) { 
                // codeFusion 目录下的-平台自定义二维码识别规则
                connectorID = url_arr.connectorID;
            } else {
                // ('未能识别二维码2')
                return {
                    err: true
                };
            }
        }else if(RexJw4.test(code)){
            const rexArr = code.split('.') 
            const gunArr =   rexArr[0].split('//')               
            pileNo = ''      
            gunNo = gunArr[1]   
            jw = regJw.test(gunNo)     
        } else if(RexYsc2Code.test(code)){// 椰速充
			console.log('=====RexYsc2Code',code)

			const urlArr = code.split('/')  
			const pileArr = urlArr[3]
			pileNo = pileArr.split('?')[0]
			console.log(urlArr,'urlArr',pileNo)  
			// pileNo = -1
			// gunNo = rexArr[1]
		 } else if (RexJw2.test(code)) {
			// 泰明-适配蔚景云二维码 格式2 互联互通  // 'hlht://ConnectorID.MA59G0765/桩编号?orgNo=桩运营商ID'
			const rexArr = result.match(/hlht:\/\/(.*)\./);
			pileNo = -1;
			gunNo = rexArr[1];
		} else if (RexHLHT2.test(code)) { //互联互通-车电网
			const rexArr = code.match(/hlht:\/\/(.*)\./)
			pileNo = -1
			gunNo = rexArr[1]
		} else if (RexGw1.test(code)) { //互联互通-国网
			decode2(code);
			return;
		} else if (RexHLHTLX.test(code)) {
			// 理想规则：如：hlht://MA7EBGWBX/81022231.MA6ARPET9/
			const rexArr = code.match(/hlht:\/\/.*\/(.*)\..*\//);
			pileNo = '';
			gunNo = rexArr[1]; // 81022231
		} else if (RexHLHT.test(code)) {
			//互联互通 'hlht://112332211.运营商ID/'
			const rexArr = code.match(/hlht:\/\/(.*)\./);
			pileNo = '';
			gunNo = rexArr[1];
		} else if (RexQMX.test(code)) {
			const rexArr = code.match(/(\d+)/g);
			pileNo = '';
			gunNo = rexArr[0];
		} else if (RexSJ.test(code)) { 
			//省交 'hlht://connector_id.EquipmentOwnerID/gunid'
			//   console.log('shengjiao',code.match(/hlht:\/\/(.*)\.(.*)\/(.*)/))
			const rexArr = code.match(/hlht:\/\/(.*)\.(.*)\/(.*)/)
			console.log('rexArr',rexArr)
			const str = rexArr[1]
			pileNo =  str.slice(0,str.length-2) 
			gunNo = parseInt(str.slice(str.length-2))
			console.log(str,'str')
			console.log(gunNo,'gunNo')
			console.log(pileNo,'pileNo')
		}else if (code.length == 92) { // 国网
			decode2(code);
			return;
		} else {
			// ('未能识别二维码3')
			return {
				err: true
			};
		}

        //   截取域名解决重复枪桩问题
        let reg = new RegExp(/(\w+):\/\/([^/:]+)(:\d*)?/)
        try {
            console.log("获取域名成功",code.match(reg))
            platformNo = code.match(reg)[2];
            if(code.match(reg)[3]){
                platformNo = platformNo + code.match(reg)[3]
            }
        } catch (error) { 
            console.log('获取域名失败')
        }

        // 计费策略二轮处理
        try{
            if(pileNo.indexOf('@2') > -1){
                pileNo = pileNo.split('@')[0]
                terminalType = 2
            }
        }catch(error){
            console.log('获取二轮失败')
        }

		return {
			pileNo,
			gunNo,
			kycText,
			codeSellerType, 
			err: false,
			runYunConnectorId,
            terminalType,
            platformNo,
            connectorID
		};
	} catch (error) {
		return {
			err: true
		};
	}
} // 扫码和输入终端号之前判断是否在充电
 
function stateOfCharge(page) {
    console.log(page,'页面路径.....')
 
    //scanCode()
    // console.log(app.globalData.memberType)
    // if(app.globalData.memberType==2){
    //    scanCode()
    // }else{
    querMemberStatus().then((res) => {
        console.log(res,'查询充电接口.....');
 
        if (res.code == 0) {
            if (res.data.ifCharging) {
                // 在充电
                // uni.showModal({
                //     title: '消息提示',
                //     content: '您当前正在充电',
                //     confirmText: '充电详情',
                //     confirmColor: '#FF2E0D',
                //     success: function (r) {
                //         if (r.confirm) {
                //             // 查看充电详情
                //             uni.navigateTo({
                //                 url: `/homeSub/pages/power/power?busId=${res.data.billList[0].busId}&pileNo=${res.data.billList[0].pileNo}&gunNo=${res.data.billList[0].gunNo}`
                //             });
                //         }
                //     }
                // });
                uni.navigateTo({
                    url: '/homeSub/pages/terminal/fault/fault?pileNo=' + res.data.billList[0].pileNo +
                        '&gunno=' + res.data.billList[0].gunNo + '&status=' + 8 + '&busId=' + res.data
                        .billList[0].busId
                });
            } else {
                if (page == 'code') {
                    uni.navigateTo({
                        url: `/pages/${page}/${page}`
                    });
                } else {
                    scanCode();
                }
            }
        } else {
            uni.showModal({
                title: '温馨提示',
                content: `${res.msg || '错误001'}`,
                showCancel: false,
                confirmColor: uni.getStorageSync('textColor') || '#6DB12E',
                confirmText: '关闭',
            });
        }
    }); // }
} // 调起扫码
 
function scanCode() {
    //#ifdef H5
    if(isChangzhi()){
        if(isWeiXin()){
            initH5Config(['scanQRCode'])
            .then(jweixin =>{
                jweixin.scanQRCode({
                    needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                    scanType: ["qrCode"], // 可以指定扫二维码还是一维码，默认二者都有
                    success: function(res) {
                        // uni.showToast({
                        // 	title: JSON.stringify(res),
                        // 	icon: 'none'
                        // });
                        scanCodeFn(res.resultStr)
                    }
                })
            }).catch(err =>{
                console.log(err)
            })
    
            return
        }
    }
    
   
	if(isZshAppInH5()){
		try{
			window.qrcodeSuccess = (data) =>{
				scanCodeFn(decodeURIComponent(data))
			}
			if(uni.getSystemInfoSync().platform == 'ios'){
				window.webkit.messageHandlers.startScan.postMessage({});
			}else{
				window.android.startScan();
			}
		}catch(e){
			//TODO handle the exception
			alert(e)
		}
	}else{
		// 普通浏览器中的代码
		uni.navigateTo({
		    url: "/pages/scan-qrcode/index"
		})
	}
    //#endif
    
    //#ifdef APP-PLUS || MP-WEIXIN || MP-ALIPAY
    uni.scanCode({
    	scanType:['qrCode'],
    	autoDecodeCharset:true,
    	success: (res) => {
    		scanCodeFn(res.result)
    	}
    })
    //#endif
} // 后台解析码

function scanCodeFn(result){
	console.log(result,'result')
	
	jw = ''     // 清空巨湾规则校验缓存
	sellerNoGy = ''       
	let codeObj = analysis(result);
	console.log(codeObj,'codeObjcodeObjcodeObj')
	
	
	if(codeObj.runYunConnectorId){
		// 巨湾润云解析
		decode4(codeObj.runYunConnectorId)
	} else if(codeObj.terminalType === 2) {
        uni.navigateTo({
            url: `/homeSub/pages/eBikeSiteDetail/eBikeSiteDetail?pileNo=${codeObj.pileNo}&gunNo=${codeObj.gunNo}`
        });
    } else{
		fn(codeObj)
	}
	
	function fn(codeObj){
		console.log(codeObj,'ewm对象....');
		    
		const regXJ = /^[a-zA-Z]+.*/
		let xj = regXJ.test(codeObj.gunNo) // 小桔验证规则
		
		//兼容特来电桩体号带字母
		const regTld = /.*[a-zA-Z]$/
		let tld = regTld.test(codeObj.gunNo)
		if (!codeObj.err) {  
			const { sellerNo } = getApp().globalData
            if (sellerNoGy) {
                // 截取商户号
                let engRegex = /[a-zA-Z]/g
                let engArr = sellerNoGy.match(engRegex)
                sellerNoGy = engArr ? engArr.join('') : ''
                console.log('-----截取到的商户号----', sellerNoGy)
            }
            // 20241218 不用前端判断，改成后端判断，所以注释这段代码
			// if(sellerNoGy && sellerNoGy != sellerNo){
			// 	return uni.showModal({
			// 		title: '提示',
			// 		content: '该充电桩不属于本平台商家，请确认后使用',
			// 		showCancel: false,   
			// 		success: function (res) {
			// 			if (res.confirm) {
			// 				console.log('用户点击确定');     
			// 			} else if (res.cancel) {
			// 				console.log('用户点击取消');
			// 			}
			// 		}
			// 	})    
			// }   
			if (codeObj.gunNo === 0) {
				codeObj.gunNo = '0'
			}
		
			//if(codeObj.gunNo&&codeObj.gunNo>=0){
			if ((codeObj.gunNo && codeObj.gunNo > -1) || codeObj.connectorID || xj || tld || jw) {      
				console.log(codeObj,'codeObj',codeObj.gunNo)
				// uni.navigateTo({
				// 	url: "/homeSub/pages/terminal/gunDetail/gunDetail?pileNo=" + codeObj
				// 		.pileNo + "&gunNo=" + codeObj.gunNo + "&kycText=" + codeObj.kycText + "&platformNo=" + codeObj.platformNo
				// })

                // 新处理
                let urlPath = '/homeSub/pages/terminal/gunDetail/gunDetail'
                const urlKey = ['pileNo', 'gunNo', 'kycText', 'platformNo', 'connectorID'] // 跳转参数-有值才携带
                urlPath = joinUrlParams(urlPath, codeObj, urlKey)
				uni.navigateTo({
					url: urlPath
				})
			} else {
				// uni.navigateTo({
				// 	url: "/echartsPages/pages/terminal/pileDetail/pileDetail?pileNo=" + codeObj.pileNo + "&codeSellerType=" + codeObj.codeSellerType + "&platformNo=" + codeObj.platformNo
				// })

                // 新处理
                let urlPath = '/echartsPages/pages/terminal/pileDetail/pileDetail'
                const urlKey = ['pileNo', 'codeSellerType', 'platformNo'] // 跳转参数-有值才携带
                urlPath = joinUrlParams(urlPath, codeObj, urlKey)
				uni.navigateTo({
					url: urlPath
				})
			}
		} else {
			decode1(result)
		}
	}
}
function decode1(qrCode) {
    parseCode({
        qrCode: qrCode
    }).then((res) => {
        if (res.code === 0) {
            const obj = res.data;
            uni.navigateTo({
                url: `/homeSub/pages/terminal/gunDetail/gunDetail?pileNo=${obj.pileNo}&gunNo=${obj.gunNo}&platformNo=${obj.platformNo}`
            });
        } else {
            uni.showModal({
                title: '提示',
                content: `${res.msg || '未能识别的二维码'},code:${res.code}`,
                showCancel: false
            });
        }
    });
}
 
// 后台解析码2--国网、能瑞
function decode2(qrCode) {
    queryQrcodeData({
        qrCode
    }).then((res) => {
        if (res.code === 0) {
            const obj = res.data
            // 国网充电
            let hasStateGrid = 1
            uni.navigateTo({
                url: `/homeSub/pages/terminal/gunDetail/gunDetail?pileNo=${obj.pileNo}&gunNo=${obj.gunNo}&hasStateGrid=${hasStateGrid}&qrCode=${encodeURIComponent(qrCode)}&platformNo=${obj.platformNo}`
            })  
        } else {
            uni.showModal({
                title: '提示',
                content: `${res.msg || '未能识别的二维码'},code:${res.code}`,
                showCancel: false
            })
        }
    })
}
 
// 后台解析码3 保泽
function decode3(qrCode) {
    queryQrcodeData({
        qrCode
    }).then((res) => {
        if (res.code === 0) {
            const obj = res.data
            uni.navigateTo({
                url: `/homeSub/pages/terminal/gunDetail/gunDetail?pileNo=${obj.pileNo}&gunNo=${obj.gunNo}&platformNo=${obj.platformNo}`
            })
        } else {
            uni.showModal({
                title: '提示',
                content: `${res.msg || '未能识别的二维码'},code:${res.code}`,
                showCancel: false
            })
        }
    })
}

// 后台解析码4 巨湾润云
function decode4(connectorId) {
	getGunDTOByConnectorId(connectorId).then(res=>{
		console.log(res,'这是润云解析返回对象')
		if(res.code == 0){
			let obj = {
				pileNo:res.data.pile.pileNum,
				gunNo:res.data.number
			}
			uni.navigateTo({
				url: `/homeSub/pages/terminal/gunDetail/gunDetail?pileNo=${obj.pileNo}&gunNo=${obj.gunNo}`
			})
		} else {
			uni.showModal({
				title: '提示',
				content: `${res.msg || '未能识别的二维码'},code:${res.code}`,
				showCancel: false
			})
		}
	})
}


/**
 * 拼接Url参数
 * @param {*} url 页面地址
 * @param {*} dataObj 数据对象
 * @param {*} joinKeyList 拼接键名列表
 * @returns 拼接完成的url，dataObj 没值的字段不拼接
 */
function joinUrlParams(url, dataObj, joinKeyList) {
	let path = url
	joinKeyList.forEach(keyName => {
        if (dataObj[keyName]) {
            const str = path.indexOf('?') > -1 ? '&' : '?'
            path += `${str}${keyName}=${dataObj[keyName]}`
        }
    })
    console.log('完整跳转链接：', path);
	return path
}

module.exports = {
	stateOfCharge,
	scanCode,
	scanCodeFn
};
